package com.corn.flink.lesson1;

import cn.hutool.core.io.FileUtil;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.lang.reflect.Type;
import java.util.Arrays;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2022/7/19 18:04
 */

public class FlinkStreamWordCount {

    public static void main(String[] args) throws Exception {
        // 1. 创建流式处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 2. 读取数据
        String filePath = FileUtil.getAbsolutePath("classpath:input/wordcount.txt");
        DataStreamSource<String> dataStreamSource = env.readTextFile(filePath);
        // 3.调用flatMap做业务处理
        SingleOutputStreamOperator<Tuple2<String, Long>> wordTupleStream = dataStreamSource.flatMap((String input, Collector<Tuple2<String, Long>> out) -> {
            String[] word = input.split(" ");
            for (String s : word) {
                out.collect(Tuple2.of(s, 1L));
            }
        }).returns(Types.TUPLE(Types.STRING, Types.LONG));
        // 4. 调用by key 进行分组聚合
        SingleOutputStreamOperator<Tuple2<String, Long>> result = wordTupleStream.keyBy(data -> data.f0)
                .sum(1);
        // 5. 调用print打印
        result.print();
        // 6. 执行环境
        env.execute();

    }
}
